<template>
  <view class="cameraBg">
    <view
      style="
        display: flex;
        font-weight: 800;
        height: 100rpx;
        align-items: center;
        justify-content: center;
        font-size: 40rpx;
      ">
      隐码识别
    </view>
    <view
      style="
        display: flex;
        font-weight: 400;
        font-size: 24rpx;
        margin-top: 20rpx;
        margin-left: 20rpx;
      ">
      校准提示：{{ tip }}
    </view>
    <camera
      mode="normal"
      style="width: 100%; height: 400rpx; margin-top: 20rpx"
      sdevice-position="back"
      flash="off"
      resolution="original"
      output-dimension="max"
      frame-size="medium"
      @initdone="initCamera">
      <cover-view class="scanBtn" v-if="scanShow"></cover-view>
    </camera>
    <view style="display: flex; justify-content: center; margin-top: 20rpx">
      请保持图片清晰，并且保证图片完整的出现在摄像框内！
    </view>
    <canvas canvas-id="mycanvas"></canvas>
  </view>
</template>
<script>
export default {
  data() {
    return {
      scanShow: true,
      listener: "",
      canvasContext: "",
      cameraContext: "",
      frame: "",
      tip: "",
    };
  },
  onLoad() {
    this.cameraContext = uni.createCameraContext();
    // this.initCamera()
    // this.initFrame()
  },
  methods: {
    // async initFrame() {
    // 	this.canvas = await this.getCanvasEl('mycanvas')
    // 	console.log("aaaaaa:", this.canvas)
    // 	this.ctx = this.canvas.getContext('2d')
    // 	let listen = this.cameraContext.onCameraFrame((frame) => {
    // 		if (this.count < 10) console.log(frame)
    // 		this.count++
    // 		this.canvas.width = frame.width
    // 		this.canvas.height = frame.height
    // 		let data = new Uint8Array(frame.data);
    // 		let clamped = new Uint8ClampedArray(data);
    // 		for (let i = 0; i < clamped.length; i += 4) {
    // 			clamped[i] = clamped[i] + 100
    // 			clamped[i + 1] = clamped[i + 1] + 50
    // 			clamped[i + 2] = clamped[i + 2] + 50
    // 			clamped[i + 3] = clamped[i + 3] + 50
    // 		}
    // 		let imageData = this.canvas.createImageData(clamped, frame.width, frame.height);
    // 		this.ctx.putImageData(imageData, 0, 0, 0, 0, frame.width, frame.height);
    // 	})
    // 	listen.start()
    // },
    initCamera(event) {
      this.$nextTick(function () {
        this.cameraContext.setZoom({
          zoom: 2.0,
          success: (res) => {
            this.getStorage();
            console.log("res:", res);
          },
          fail: (e) => {
            console.log("e:", e);
            this.getStorage();
          },
        });
      });
    },
    getStorage() {
      let _that = this;
      wx.getSetting({
        success(res) {
          if (res.authSetting["scope.camera"]) {
            _that.takePhoto();
          } else {
            wx.authorize({
              scope: "scope.camera",
              success() {
                _that.takePhoto();
              },
              fail() {
                _that.takePhoto().goBack();
              },
            });
          }
        },
      });
    },
    //拍照
    takePhoto() {
      let vm = this;
      this.cameraContext.takePhoto({
        quality: "original",
        success: (res) => {
          var url = res.tempImagePath;
          // this.save(url);
          this.upLoad(url);
          // vm.drawCroppedImage(url);
          console.log("拍照成功", url);
        },
        fail: (err) => {
          vm.tip = "拍照失败:" + err;
        },
      });
    },
    //上传
    upLoad(urls) {
      let _vm = this;
      console.log("上传一张图片");
      const uploadTask = uni.uploadFile({
        // url: "http://124.70.161.202:8063",
        // url: "http://47.104.227.45:8063",
        url: "https://m.asy315.vip/smear/detect",
        // url: "http://192.168.43.117:8063",
        // url:"http://asy.nat300.top/biz/common/upload",
        // header: {
        // 	"biz-token": "b24b2730-2ce4-454f-b501-e965def5d022",
        // },
        filePath: urls,
        formData: {
          id: "1702887314888888",
          type: 2,
        },
        name: "file",
        success: function (uploadRes) {
          if (uploadRes.data) {
            console.log("识别成功源数据：", uploadRes.data);
            let result = JSON.parse(uploadRes.data);
            console.log("JsonParse：", result);
            if (result.status == 200) {
              if (!result.data || !result.data.label) {
                _vm.tip = "解析";
                _vm.takePhoto();
              } else {
                _vm.goBack(result);
              }
            } else {
              console.log("识别失败：", result);
              if (result.status == 1) {
                _vm.tip =
                  "图片定位失败,请保持图像完整纳入扫描框,并保持图片清晰";
              } else if (result.status == 2) {
                _vm.tip = "发现图片旋转、倾斜,请保持图片水平端正";
              } else if (result.status == 3) {
                _vm.tip = "服务器连接失败";
              }
              _vm.takePhoto();
            }
          } else {
            console.log("数据为空：", result);
            _vm.takePhoto();
          }
        },
        fail: function (err) {
          console.log("识别失败：", err);
          if (err.errno == 600001) {
            _vm.goBack(err);
          } else {
            _vm.takePhoto();
          }
        },
        complete: function (err) {
          // console.log("upload complete", err);
        },
      });
      uploadTask.onHeadersReceived((res) => {
        console.log("接收数据:" + res);
      });
      uploadTask.onProgressUpdate((res) => {
        // console.log("数据:" + res);
        // console.log("上传进度:" + res.progress);
        console.log("已经上传的数据长度:" + res.totalBytesSent);
        // console.log("预期需要上传的数据总长度:" + res.totalBytesExpectedToSend);
      });
    },
    //保存
    save(imgUrl) {
      let fileName = new Date().valueOf();
      let _this = this;
      console.log("开始相册", imgUrl);
      wx.getImageInfo({
        src: imgUrl,
        success: function (res) {
          console.log("获取图片成功", res);
          wx.saveImageToPhotosAlbum({
            filePath: res.path,
            success: function (res) {
              console.log("保存相册：", res);
              _this.takePhoto();
            },
            fail: function (e) {
              console.log("保存失败：", e);
            },
          });
        },
        fail(res) {
          console.log("获取图片失败", res);
        },
      });
    },
    goBack(data) {
      uni.$emit("isRefresh", data);
      uni.navigateBack({
        delta: 1,
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.cameraBg {
  width: 100%;
  height: 100vh;
  position: fixed;

  .scan-img {
    width: 100%;
    height: 1624rpx;
    z-index: 1;
  }

  .scanBtn {
    width: 100%;
    z-index: 99999;
    position: fixed;
    bottom: 100rpx;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    .beat {
      position: absolute;
      bottom: 0rpx;
      left: 100rpx;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      font-size: 24rpx;
      font-weight: 400;
      color: #ffffff;

      .beatImg {
        width: 88rpx;
        height: 88rpx;
        margin-bottom: 30rpx;
      }
    }

    .album {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      font-size: 24rpx;
      font-weight: 400;
      color: #ffffff;

      .albumImg {
        width: 120rpx;
        height: 120rpx;
        margin-bottom: 30rpx;
      }
    }
  }
}
</style>
